// 引入配置
import config from '@/util/config.js'

import {HubConnection} from '@/util/signalr.js'

import {
	defineStore
} from "pinia";

export const commonStore = defineStore("common", {
	state: () => {
		return {
			Authorization: '',
			userdetail: {
				id: 0,
				currentpackid: 0,
				username: "未登录",
				mobile: null,
				packname: null
			},
			connection: null,
			connectionState: true,
			upLoadPhoto: true,
			goodsList: [], //临时储存选择的品类信息
			info:{
				userid: 0,
				enterpriseid: 0,
				id: 0
			}, //临时储存用户信息
			permissions: [],
			goodsDetails: []
		};
	},
	getters: {},
	actions: {
		// 扫码与刷卡登录
		login(obj){
			this.initSocket()
			return new Promise((resolve, reject)=>{
				console.log('obj',obj)
				let api = ''
				if(obj.type == 'scan'){ //扫码登录
					api = 'Pack/QrCode/Login'
				}else if(obj.type == 'IC'){ //读卡器登录
					api = 'Iot/IC/Login'
				}
				console.log('loginApi',api,obj.code)
				uni.showLoading({
					title: '登录中...'
				})
				uni.$u.http.post(api, {
					"code": obj.code
				}).then(res => {
					console.log(res)
					if(res.datas){
						let staffinfo = res.datas.staffinfo
						let userdetail = {
							mobile: staffinfo.mobile,
							username: staffinfo.name,
							usestate: staffinfo.usestate,
							currentpackid: staffinfo.packstation?.id,
							packname: staffinfo.packstation.name
						}
						this.Authorization = res.datas.token
						this.userdetail = userdetail
						this.permissions = staffinfo.permission
						
						uni.setStorageSync('Authorization',this.Authorization)
						uni.setStorageSync('userdetail',this.userdetail)
						uni.setStorageSync('permissions',this.permission)
						uni.setStorageSync('loginTime',new Date().getTime())
						uni.setStorageSync('loginCode',obj.code)
						console.log('lifeData',this.Authorization,this.userdetail,this.permissions)
						
						this.signalrConnection()
					}
					resolve(res)
				}).catch(err => {
					console.log('err',err)
					try {
						uni.showToast({
							icon:'error',
							title: err.msg
						})
					} catch (error) {
						//TODO handle the exception
					}
					reject(err)
				}).finally(()=>{
					uni.hideLoading()
				})
			})
		},
		// 判断登录超时
		isLoginTimeOut(){
			return new Promise((resolve, reject)=>{
				try {
					let loginTime = uni.getStorageSync('loginTime');
					
					if (loginTime) {
						// 登录时间过去在24小时内,则插入Storage信息并连接websocket
						// if(new Date().getTime() - loginTime < 24*60*60*1000){
							
							try {
								const userdetail = uni.getStorageSync('userdetail');
								const Authorization = uni.getStorageSync('Authorization');
								if (userdetail||Authorization) {
									this.userdetail = userdetail
									this.Authorization = Authorization
									// this.initSocket()
									// this.signalrConnection()
									// uni.redirectTo({
									// 	url: '/pages/index/index'
									// })
									resolve()
								}
							} catch (e) {
								this.Authorization = ''
								this.userdetail = {
									id: 0,
									currentpackid: 0,
									username: "未登录",
									mobile: null,
									packname: null
								}
								this.userdetail.packname = ''
								uni.removeStorageSync('Authorization')
								uni.removeStorageSync('userdetail')
								uni.removeStorageSync('loginTime')
								uni.removeStorageSync('loginCode')
								
								// uni.redirectTo({
								// 	url: '/pages/index/index'
								// })
								reject()
							}
						// }else{
						// 	uni.removeStorageSync('Authorization')
						// 	uni.removeStorageSync('userdetail')
						// 	uni.redirectTo({
						// 		url: '/pages/index/index'
						// 	})
						// }
					}else{
						throw Error('outLogin')
					}
				} catch (e) {
					uni.redirectTo({
						url: '/pages/index/index'
					})
				}
			})
		},
		//全局监听ws
		initSocket(){
			//全局监听ws连接返回
			uni.onSocketMessage((res) => {
				let msgData = {}
				try{
					let msg = res.data.replace(String.fromCharCode(0x1e), ""); //替换消息结束符
					msgData = JSON.parse(msg)
				}catch(e){
					// console.log(e)
				}
				
				// 有效数据
				if(msgData.target){
					console.log(msgData.target,res)
				}
				
				// 此处做一个防抖处理，以防重复连接websocket时同时触发多次方法
				uni.$u.throttle(()=>{
					if (msgData.type === 1 && msgData.target == "reload") {
						console.log('收到重连要求')
						// common.signalrConnection()
					}
					if (msgData.type === 1 && (msgData.target == "interactive" || msgData.target == "ExamineOderRemind")) {
						console.log('收到服务器发送的内容：' + msgData.arguments[0]?.type,msgData.arguments[0]?.data);
						// 手机发送指令到一体机要求打印小票时
					}
				},100)
			});
		},
		// 在线推送信息
		signalrConnection(){
			if(this.connection != null || this.Authorization == ''){
				return
			}
			this.connection = new HubConnection();
			console.log('ws心跳间隔时间',this.connection.timeInterval)
			console.log('ws连接状态',this.connection.openStatus)
			//注意：这里的config.baseURL不是wss或ws，是https或http
			this.connection.start(`${config.baseURL}/pushed`, {
				Terminal: 'AIO',
				ClientId: uni.getDeviceInfo().deviceId,
				access_token: this.Authorization
			});

			this.connection.onOpen = res => {
				uni.showToast({
					title: '已开启连接',
					icon:'none'
				});
				this.connectionState = true
			}
			
			this.connection.onClose = res => {
				uni.showToast({
					title: '连接已关闭',
					icon:'none'
				});
				this.connectionState = false
			}
			
			this.connection.onReconnect = res =>{
				console.log('尝试重新连接...')
				this.connection = new HubConnection();
				this.connection.start(`${config.baseURL}/pushed`, {
					Terminal: 'AIO',
					ClientId: uni.getDeviceInfo().deviceId,
					access_token: this.Authorization
				});
			}
			
			this.connection.receive = msgData => {
				// 此处做一个防抖处理，以防重复连接websocket时同时触发多次方法
				uni.$u.throttle(()=>{
					console.log('connection.receive',msgData,new Date())
					if (msgData.type === 1 && msgData.target == "reload") {
						console.log('收到重连要求')
					}
				},100)
			}
		}
	}
});